<template>
  <a-drawer
    :open="tagVisible"
    class="dmp-tag-options-drawer"
    width="320px"
    force-render
    :title="tagIsSearch ? '' : '标签管理'"
    placement="right"
    @close="closeDrawer"
  >
    <template #extra>
      <div class="tag-tab">
        <div v-if="!tagIsSearch" class="no-search">
          <div>
            <span class="search-icon" @click="showTagIsSearch(true)"><i class="iconfont icon-search-line"></i></span>
            <span class="add-btn" @click="handleOpenTagForm()">
              <i class="iconfont icon-add-line"></i>
            </span>
          </div>
        </div>
        <div v-else class="search">
          <a-input
            ref="inputRef"
            v-model:value="tagSearchValue"
            v-trim
            allow-clear
            placeholder="请输入标签"
            style="width: 250px"
            @keyup.enter="getTaskTag(taskInfo.id)"
            @blur="showTagIsSearch(false)"
            @keydown.stop=""
          >
            <template #prefix>
              <i class="iconfont icon-search-line"></i>
            </template>
            <!-- <template #suffix>
              <div @click=";(tagSearchValue = ''), (tagIsSearch = false), getTaskTag(taskInfo.id)" class="close-search-btn">
                <close-circle-filled />
              </div>
            </template> -->
          </a-input>
        </div>
      </div>
    </template>
    <div class="tag-options-box">
      <div class="tag-column">
        <div class="name">名称</div>
        <div class="attribute">属性</div>
      </div>
      <div class="tag-list my-scrollbar">
        <div
          v-for="(item, index) in tagList"
          :key="item.id"
          class="tag-li"
          @mouseover="hoverTagIndex = index"
          @mouseleave="hoverTagIndex = undefined"
        >
          <div class="fixed-label">
            <i v-if="fixedTagId == item.id" class="iconfont icon-pushpin-fill" @click=";(fixedTagId = null), changeMarkDrawStyle()"></i>
            <i
              v-else-if="hoverTagIndex == index && fixedTagId !== item.id"
              class="iconfont icon-pushpin-line"
              @click=";(fixedTagId = item.id), changeMarkDrawStyle()"
            ></i>
          </div>
          <div class="tag-name">
            <a-tooltip>
              <template #title> {{ item.name }}</template>
              <span :style="{ backgroundColor: hexToRgba(item.color, 0.375).rgba, color: item.color }">
                {{ item.name }}
              </span>
            </a-tooltip>
          </div>
          <div v-if="hoverTagIndex != index" class="content">{{ item.attributeList?.map(item => item.name).toString() }}</div>
          <div v-else-if="hoverTagIndex == index" class="hover-btn">
            <span class="btn" @click="handleEdit(item)">
              <i class="iconfont icon-equalizer-line"></i>
            </span>
            <span class="btn" @click="deleteTag(item.id)">
              <i class="iconfont icon-delete-bin-6-line"></i>
            </span>
          </div>
        </div>
      </div>
    </div>
  </a-drawer>

  <!-- 标签表单 -->
  <tag-form ref="tagFormRef" :title="tagFormTitle" :ok-btn-loading="isAddOrEditTagLoading" @onSubmit="confirmAddEditTag" />
</template>

<script setup lang="ts">
  import { Modal } from 'ant-design-vue'
  import { hexToRgba } from 'g6-fn'
  import { computed, createVNode, nextTick, ref } from 'vue'
  import { useRequest } from 'vue-request'

  import WarnIcon from '@/components/icon/IconWarn/index.vue'
  import { dmpTaskApi } from '@/services/api'

  import TagForm from '../../components/TagForm.vue'
  import { TaskTag } from '../../types'

  export interface Props {
    taskInfo: { id: string; name: string }
    markTagSearchValue: string | null | undefined
    onAfterDeleteTag: (tagId: string) => void
    onEditTagCanvasHandler: (tagId: TaskTag) => void
  }

  const props = withDefaults(defineProps<Props>(), {})

  const emits = defineEmits(['updateNowGraph'])

  const tagVisible = ref(false)
  const tagFormRef = ref()
  const tagIsSearch = ref(false)
  const hoverTagIndex = ref()
  const tagFormTitle = ref('新增标签')
  const tagSearchValue = ref()
  const fixedTagId = ref<number | string | null>()
  const tagList = ref<TaskTag[]>([])

  // 根据类型打开标签表单
  const handleOpenTagForm = () => {
    tagFormTitle.value = '新增标签'
    tagFormRef.value.open()
  }
  // 物体标注表单编辑
  const handleEdit = (row: any) => {
    tagFormTitle.value = '编辑标签'
    tagFormRef.value.setForm(row)
    tagFormRef.value.open()
  }

  // 删除标签
  const deleteTag = (tagId: string) => {
    Modal.confirm({
      title: '确定删除?',
      icon: createVNode(WarnIcon),
      content: '删除后，标签不可恢复',
      okText: '确定',
      cancelText: '取消',
      centered: true,
      onOk: async () => {
        let { data } = await dmpTaskApi.taskTagDel({}, { urlParams: { id: tagId } })
        if (data) {
          if (tagId === fixedTagId.value) {
            fixedTagId.value = null
          }
          props.onAfterDeleteTag(tagId)
        }
      }
    })
  }

  const getTaskTag = async (taskId: string, name?: string) => {
    let params = {
      taskId: taskId,
      name: name ?? tagSearchValue.value
    }
    let { data } = await dmpTaskApi.taskTag(params)
    tagList.value = data
    if (data.length > 0) {
      changeMarkDrawStyle()
    }
  }
  //标签状态
  const inputRef = ref<HTMLInputElement | null>(null)

  const showTagIsSearch = (type: boolean): void => {
    tagIsSearch.value = type
    if (type) {
      nextTick(() => inputRef.value?.focus())
    }
  }
  // 改变绘制标签的样式
  const changeMarkDrawStyle = () => {
    let findIndex = tagList.value.findIndex((item: any) => item.id === fixedTagId.value)
    let color = '#1868E9'
    if (fixedTagId.value && findIndex !== -1) {
      color = tagList.value[findIndex!].color || ''
    }
    emits('updateNowGraph', {
      nowGraphFillColor: hexToRgba(color, 0.375).rgba, // 当前图形填充色
      nowGraphStrokeColor: color // 当前图形边框色
    })
  }

  /*  标签新增、编辑---------------------------------------------------------------------------------- */
  // 新增和编辑的useRequest
  const { runAsync: runEditTag, loading: isEditTagLoading } = useRequest(dmpTaskApi.taskTagEdit)
  const { runAsync: runAddTag, loading: isAddTagLoading } = useRequest(dmpTaskApi.taskTagAdd)

  const isAddOrEditTagLoading = computed(() => isEditTagLoading.value || isAddTagLoading.value)

  const confirmAddEditTag = async (data: any) => {
    const newData = { ...data, taskId: props.taskInfo.id }
    newData.attributeList = newData.attributeList.filter((item: any) => item?.name?.trim() !== '')
    const run = newData.id ? runEditTag : runAddTag
    await run(newData, { isAddUid: true })
    tagFormRef.value.close()
    await getTaskTag(props.taskInfo.id)
    props.onEditTagCanvasHandler(tagList.value.find(tag => tag.name === newData.name)!)
  }
  /*  ---------------------------------------------------------------------------------- */

  const closeDrawer = () => {
    console.log(1111)

    tagVisible.value = false
    tagIsSearch.value = false
    tagSearchValue.value = ''
    getTaskTag(props.taskInfo.id)
  }
  const openDrawer = () => {
    tagVisible.value = true
  }

  defineExpose({
    getTaskTag,
    tagList,
    fixedTagId,
    tagVisible,
    open: openDrawer,
    close: closeDrawer
  })
</script>
<style lang="less">
  .dmp-tag-options-drawer {
    .ant-drawer-wrapper-body {
      .ant-drawer-header {
        padding: 12px 20px;
        height: 60px;

        .ant-drawer-close {
          font-size: 14px;
        }

        .ant-drawer-title {
          font-size: 14px;
        }
      }

      .ant-drawer-body {
        padding: 0;
      }
    }
  }
</style>

<style lang="less" scoped>
  .tag-tab {
    display: flex;
    align-items: center;
    height: 66px;

    .no-search {
      display: flex;
      justify-content: space-between;
      align-items: center;

      .name {
        color: rgba(25, 25, 48, 0.75);
        .font14b();
      }

      .add-btn {
        display: inline-block;
        margin-left: 17px;
        width: 26px;
        height: 26px;
        font-size: 16px;
        text-align: center;
        color: rgba(25, 25, 48, 0.75);
        border-radius: 6px;
        line-height: 26px;
        cursor: pointer;

        &:hover {
          background: rgba(0, 0, 0, 0.05);
        }
      }

      .search-icon {
        display: inline-block;
        width: 26px;
        height: 26px;
        font-size: 16px;
        text-align: center;
        color: rgba(25, 25, 48, 0.75);
        cursor: pointer;
        line-height: 26px;
        border-radius: 6px;

        &:hover {
          background: rgba(0, 0, 0, 0.05);
        }
      }
    }

    .search {
      .close-search-btn {
        cursor: pointer;
        color: rgba(25, 25, 48, 0.75);
      }
    }
  }

  .tag-options-box {
    width: 320px;
    height: 100%;
    border-left: 1px solid #d9d9db;

    .tag-column {
      display: flex;
      align-items: center;
      padding: 11px 0 11px 40px;
      height: 40px;
      border-bottom: 1px solid #e8e8eb;

      .name {
        padding-left: 8px;
        width: 92px;
      }

      .attribute {
        display: flex;
        align-items: center;
        padding-left: 8px;
        width: calc(100% - 92px);
      }
    }

    .tag-list {
      overflow-y: auto;
      padding: 8px 0;
      margin-top: 8px;
      height: calc(100% - 106px - 16px);

      .tag-li {
        position: relative;
        display: flex;
        align-items: center;
        margin-bottom: 8px;
        height: 44px;
        cursor: default;

        &:hover {
          background: #f5f5f5;
        }

        &--active {
          background: #f5f5f5;
        }

        .fixed-label {
          padding: 0 5px 0 17px;
          width: 40px;
          font-size: 18px;
          flex-shrink: 0;
          cursor: pointer;

          .iconfont.icon-pushpin-fill {
            color: @primary1;
          }

          .iconfont.icon-pushpin-line {
            color: rgba(25, 25, 48, 0.45);
          }
        }

        .tag-name {
          padding: 0 8px;
          width: 94px;
          box-sizing: border-box;

          span {
            display: inline-block;
            padding: 3px 6px;
            .elliptical-1();

            width: 78px;
            height: 28px;
            text-align: left;
            color: #1868e9;
            background: rgba(24, 104, 233, 0.08);
            border: 1px solid rgba(0, 0, 0, 0.05);
            border-radius: 6px;
            line-height: 22px;
          }
        }

        .content {
          padding: 0 24px 0 8px;
          .elliptical-1();
        }

        .hover-btn {
          position: absolute;
          right: 24px;

          .btn {
            display: inline-block;
            width: 26px;
            height: 26px;
            font-size: 14px;
            text-align: center;
            color: rgba(16, 16, 20, 0.95);
            border-radius: 6px;
            cursor: pointer;
            line-height: 26px;

            &:hover {
              background: rgba(0, 0, 0, 0.05);
            }

            &:last-child {
              margin-left: 16px;
            }
          }
        }
      }
    }
  }
</style>
